package com.tedu.jdbc;

import com.tedu.utils.JDBCUtils;

import java.sql.*;
import java.util.Scanner;

/**
 * Created by IntelliJ IDEA.
 *
 * @author zq
 * @version 1.0
 * @create 2024-07-30 16:27
 * @since jdk1.8
 */
public class JDBCRegister {
    static Connection conn = null;
    static PreparedStatement ps = null;
    static ResultSet rs = null;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        try {
            conn = JDBCUtils.getConnection();
            System.out.println("请输入用户名：");
            String username = sc.nextLine();
            //调用判断用户名是否存在方法
            boolean next = isUsernameExists(conn, username);
            if (next) {
                System.out.println("用户名已存在");
                return;
            }
            System.out.println("请输入密码：");
            String password = sc.nextLine();
            System.out.println("请输入昵称");
            String nickname = sc.nextLine();
            System.out.println("请输入年龄");
            int age = sc.nextInt();
            //调用注册用户方法
            int count = registerUser(conn, username, password, nickname, age);
            if (count > 0) {
                System.out.println("注册成功");
            } else {
                System.out.println("注册失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close(rs, ps, conn);
        }

    }

    public static boolean isUsernameExists(Connection conn, String username) throws SQLException {
        String select = "select * from userinfo where username=?";
        ps = conn.prepareStatement(select);
        ps.setString(1, username);
        rs = ps.executeQuery();
        boolean next = rs.next();
        return next;
    }

    public static int registerUser(Connection conn, String username, String password, String nickname, int age) throws SQLException {
        String insert = "insert into userinfo(username,password,nickname,age) values(?,?,?,?)";
        ps = conn.prepareStatement(insert);
        ps.setString(1, username);
        ps.setString(2, password);
        ps.setString(3, nickname);
        ps.setInt(4, age);
        int count = ps.executeUpdate();
        return count;
    }
}
